package com.gy.edu.teach.adapter;


import android.content.Context;
import android.graphics.Point;
import android.graphics.PointF;
import android.os.AsyncTask;
import android.support.v4.view.PagerAdapter;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;

import com.artifex.mupdf.MuPDFCore;
import com.artifex.mupdf.MuPDFPageView;
import com.gy.edu.MyApplication;
import com.gy.edu.util.ListViewItemListener;

/** ��ҳviewpager adapter*/
public class TeachPagerAdAdapter extends PagerAdapter {

	private Context context;
	private int flag = 1;
	private ListViewItemListener listener;
	private final MuPDFCore mCore;
	private final SparseArray<PointF> mPageSizes = new SparseArray<PointF>();

	public TeachPagerAdAdapter(Context context, MuPDFCore core) {
		this.context = context;
		this.mCore = core;
	}
	
	public void setFlag(int flag){
		this.flag = flag;
	}
	
	public void setListener(ListViewItemListener listener){
		this.listener = listener;
	}

	@Override
	public boolean isViewFromObject(View arg0, Object arg1) {
		// TODO Auto-generated method stub
		return arg0 == arg1;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return mCore.countPages();
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		/*
		 * if (list.size() > 0) { if(null != mViewList.get(position))
		 * container.removeView(mViewList.get(position)); }
		 */
	}

	@Override
	public int getItemPosition(Object object) {
		return super.getItemPosition(object);
	}

	@Override
	public Object instantiateItem(ViewGroup container, final int position) {
		final MuPDFPageView pageView;
		PointF pageSize = mPageSizes.get(position);
		pageView = new MuPDFPageView(context, mCore, new Point(MyApplication.screenWidth,MyApplication.screenHeight));
		if(pageSize != null){
			pageView.setPage(position, pageSize);
		}else{
			pageView.blank(position);
			AsyncTask<Void,Void,PointF> sizingTask = new AsyncTask<Void,Void,PointF>(){
				@Override
				protected PointF doInBackground(Void... arg0){
					return mCore.getPageSize(position);
				}
				@Override
				protected void onPostExecute(PointF result){
					super.onPostExecute(result);
					mPageSizes.put(position, result);
					if (pageView.getPage() == position)
						pageView.setPage(position, result);
				}
			};
			try{
				sizingTask.execute((Void)null);
			}
			catch (java.util.concurrent.RejectedExecutionException e){
				PointF result = mCore.getPageSize(position);
				mPageSizes.put(position, result);
				if (pageView.getPage() == position)
					pageView.setPage(position, result);
			}
		}
		container.addView(pageView,0);
		return pageView;
	}

}
